package cn.hdu.charge.service;

import cn.hdu.charge.dao.UserDao;
import cn.hdu.charge.domain.User;
import cn.hdu.utils.commons.CommonUtils;

import java.math.BigDecimal;
import java.sql.SQLException;

/**
 * 用户模块业务层
 */
public class UserService {

    private UserDao userDao = new UserDao();

    public void regist(User user) {
        /**
         * 1.补齐其他数据
         */
        user.setUserId(CommonUtils.uuid());
        user.setBalance(BigDecimal.valueOf(0));

        /**
         * 2.userDao把记录保存到数据库中
         */
        try {
            userDao.add(user);
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }

    }

    public User login(User user) {
        try {
            return userDao.findByMobileAndPassword(user.getMobile(), user.getPassword());
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean updatePassword(String userId, String oldPassword, String newPassword) throws MyException {
        try {
            boolean bool = userDao.findByuserIdAndPassword(userId, oldPassword);
            if(!bool) {
                throw new MyException("老密码错误");
            }
            userDao.updatePassword(userId, newPassword);
            return true;
        } catch(SQLException e) {
            return false;
        }
    }

    public boolean chargeBlance(String userId, BigDecimal blance) {
        try {
            userDao.chargeBlance(userId, blance);
            return true;
        } catch(SQLException e) {
            return false;
        }
    }

    /**
     * mobile校验
     */
    public boolean ajaxValidateMobile(String mobile) {
        try {
            return userDao.ajaxValidateMobile(mobile);
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
